<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminController as Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request; 
use App\Model\{Admin,User,Config,Cat,Usertree}; 
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use App\Libraries\vendor\Sms;
use GeoIp2\Database\Reader;
use App\Libraries\vendor\SphinxClient;

/**
 * @menu_cat 会员
 * @icon cog
 * @sort 30
 */
class UserController extends Controller
{
	public function __invoke(){
        return $this->index(func_get_args());
    }

    /**
     * @menu 所有会员
     * @return [type] [description]
     */
    public function index(){
        $order = request()->input('_order');
        $orders = [];
        if($order){
            $order = explode('|', $order);
            foreach($order as $k=>$v){
                if(!$v){ continue; }
                $tmp = explode('=', $v);
                $orders[$tmp[0]] = $tmp[1];
            }
        }
        if(isset($orders['money_all'])){
            return $this->indexByMoneyAll($orders['money_all']);
        }

    	$list = DB::table('user_tree');
    	$this->_search($list, $search);
        if(!empty($search['tree_id']) && !empty($search['left']) && !empty($search['right']) && !empty($search['hight'])){

            ##$top = DB::table('user_tree')->where('tree_id',$search['tree_id'])->where('uid',$search['tree_id'])->first(['left','right']);
            $list->where([
                ['tree_id','=',$search['tree_id']],
                ['left','>',$search['left']],
                ['right','<',$search['right']],
                ['hight','=',$search['hight']]
            ]);
            unset($search['left']);
            unset($search['right']);
            unset($search['tree_id']);
        }
        

        $this->_order($list,['id'=>'desc']);
        $list = $list->paginate(20);
        User::separat_format($list);
        $status = Config::get_config_bykey('userdata_status');

        return view('Admin.User.index')->with([
            'list' => $list,
            '_search'=>$search,
            'status'=>$status,
        ]);
    }

    public function indexByMoneyAll($sort){
        /*
        $search = request()->input('_search');
        $search_tmp = [];
        if($search){
            $search = explode('|', urldecode($search));
            foreach($search as $k=>&$v){
                $v = explode('=', $v);
                $search_tmp[$v[0]] = $v[1];
            }
        }
        $user = DB::table('user');
        foreach($search_tmp as $k=>$v){
            $user->where($k,$v);
        }
        $ids = $user->pluck();
        */
        $list = DB::table('data_statistics')->join('user_tree','data_statistics.uid','=','user_tree.uid')
            ->orderBy('money_all',$sort);
        $list = $list->paginate(20);
        User::separat_format($list);
        $status = Config::get_config_bykey('userdata_status');
        return view('Admin.User.index')->with([
            'list' => $list,
            'status'=>$status,
        ]);
    }

    /**
     * @menu 封禁用户
     */
    public function prohibition_list(){
        $list = DB::table('userdata')->where('status',0);
        $this->_search($list, $search);
        $list->orderBy('id','desc');
        $list = $list->paginate(20);
        
        $uids = get_array_keys($list->items(),'uid');
        $profits = DB::table('data_statistics')->select('uid','money_all')->whereIn('uid',$uids)->get()->toArray();
        $profits = arrays_set_key($profits,'uid');
        foreach($list->items() as &$item) {
            $item->profit = $profits[$item->uid]->money_all;
        }

        $status = Config::get_config_bykey('userdata_status');
        return view('Admin.User.prohibition_list')->with([
            'list' => $list,
            '_search'=>$search,
            'status'=>$status,
            'title'=>'封禁用户'
        ]);
    }

    /**
     * @menu 疑似作弊用户
     */
    public function limit_list(){
        $list = DB::table('userdata')->where('status',2);
        $this->_search($list, $search);
        $list->orderBy('id','desc');
        $list = $list->paginate(20);
        
        $uids = get_array_keys($list->items(),'uid');
        $profits = DB::table('data_statistics')->select('uid','money_all')->whereIn('uid',$uids)->get()->toArray();
        $profits = arrays_set_key($profits,'uid');
        foreach($list->items() as &$item) {
            $item->profit = $profits[$item->uid]->money_all;
        }

        $status = Config::get_config_bykey('userdata_status');
        return view('Admin.User.prohibition_list')->with([
            'list' => $list,
            '_search'=>$search,
            'status'=>$status,
            'title'=>'限制用户'
        ]);
    }

    /**
     * @menu 超级会员
     */
    public function super_index(){
        $order = request()->input('_order');
        $orders = [];
        if($order){
            $order = explode('|', $order);
            foreach($order as $k=>$v){
                if(!$v){ continue; }
                $tmp = explode('=', $v);
                $orders[$tmp[0]] = $tmp[1];
            }
        }
        if(isset($orders['money_all'])){
            return $this->superByMoneyAll($orders['money_all']);
        }
        $list = DB::table('user_tree')->where('user_level',1);
        $this->_search($list, $search);
        $this->_order($list);
        $list = $list->paginate(20);
        User::separat_format($list);
        return view('Admin.User.super_index')->with([
            'list' => $list,
            '_search'=>$search,
        ]);
    }

    public function superByMoneyAll($sort){
        $list = DB::table('data_statistics')->join('user_tree','data_statistics.uid','=','user_tree.uid')
            ->where('user_tree.user_level',1)
            ->orderBy('money_all',$sort);
        $list = $list->paginate(20);
        User::separat_format($list);
        $status = Config::get_config_bykey('userdata_status');
        return view('Admin.User.super_index')->with([
            'list' => $list,
            'status'=>$status,
        ]);
    }

    /**
     * @menu 合伙人
     */
    public function separate_index(){
        $list = DB::table('user_tree')->where('user_level',2);
        $this->_search($list, $search);
        $this->_order($list);
        $list = $list->paginate(20);
        User::separat_format($list);
        $diversion = Config::get_config_bykey('user_tree_diversion');
        return view('Admin.User.separate_index')->with([
            'list' => $list,
            '_search'=>$search,
            'diversion'=>$diversion,
        ]);
    }

    /**
     * @name 查看合伙人子会员
     */
    public function nodes($id){
        $user = DB::table('user_tree')->where('uid',$id)->first();
        $info = DB::table('userdata')->where('id',$id)->first(['nickname']);
        $list = DB::table('user_tree')->where([
            ['tree_id','=',$user->tree_id],
            ['left','>',$user->left],
            ['right','<',$user->right]
        ]);
        $this->_search($list, $search);
        $this->_order($list);
        $list = $list->paginate(20);
        User::separat_format($list);
        return view('Admin.User.separate_index')->with([
            'list' => $list,
            '_search'=>$search,
            'title'=>urldecode($info->nickname).'的团队',
        ]);
    }


    /**
     * @menu 申请合伙人
     */
    public function apply_parther(){
        $list = DB::table('partner_apply');
        $this->_search($list, $search);
        if(empty($search['status'])){
            $search['status'] = 0;
            $list->where('status',0);
        }
        $this->_order($list);
        $list = $list->paginate(20);

        User::apply_parther_format($list);
        $status = Config::get_config_bykey('partner_apply_status');
        return view('Admin.User.apply_parther')->with([
            'list' => $list,
            '_search'=>$search,
            'status'=>$status,
        ]);
    }
    
    public function ajax_accept_parther($id){
        $info = DB::table('partner_apply')->where('id',$id)->first(['uid']);
        $up = User::separate_tree($info->uid);
        $bool = false;
        if($up){
            $bool = DB::table('partner_apply')->where('id',$id)->update([
                'status'=>1,
            ]);
        }
        $bool = $bool && $up;
        
        return response()->json([
            'status'=>$bool?1:0,
        ]);
    }

    public function ajax_refund_parther($id){
        $post = request()->only(['msg']);
        $bool = DB::table('partner_apply')->where('id',$id)->update([
            'status'=>2,
            'msg'=>$post['msg']
        ]);
        return response()->json([
            'status'=>$bool?1:0,
        ]);
    }   
    public function ajax_update_status($uid){
        if(request()->isMethod('post')){
            $param = request()->only(['closure_rreason','other','status']);
            $msg = "";
            if(!empty($param['other'])){
                DB::table('userdata')->where('id',$uid)->update([
                    'closure_rreason'=>$param['other'],
                    'status'=>$param['status']
                ]);
                DB::table('user_tree')->where('uid',$uid)->update(['status'=>$param['status']]);
                $msg = $param['other'];
            }else{
                DB::table('userdata')->where('id',$uid)->update([
                    'closure_rreason'=>$param['closure_rreason'],
                    'status'=>$param['status']
                ]);
                DB::table('user_tree')->where('uid',$uid)->update(['status'=>$param['status']]);
                $msg = $param['closure_rreason'];
            }
            
            #队列
            Redis::rpush('songshu:queue',json_encode([
                'work_type'=>4,
                'data'=>[
                    'type'=>$param['status']==1?2:1,
                    'id'=>$uid,
                ]
            ]));

            #添加日志
            if($param['status']==0 || $param['status']==2){
                DB::table('prohibit_log')->insert([
                    'uid'=>$uid,
                    'status'=>$param['status'],
                    'add_time'=>time(),
                    'msg'=>$msg,
                ]);
            }
            return \Redirect::back()->with('msg', '修改成功');
            return response()->json([
                'status'=>1,
                'info'=>'success'
            ]);
        }       
        $status = request()->input('status');
        $data = DB::table('userdata')->where('id',$uid)->first(['closure_rreason']);
        return view('Admin.User.ajax_update_status')->with([
            'data'=>$data,
            'uid'=>$uid,
            'status'=>$status,
            'userdata_closure_rreason'=>Config::get_config_bykey('userdata_closure_rreason')
        ]);
    }
    public function ajax_up_status($id){
        $post = request()->only(['status']);
        $bool = DB::table('userdata')->where('id',$id)->update([
            'status'=>$post['status'],
        ]);
        DB::table('user_tree')->where('uid',$id)->update([
            'status'=>$post['status'],
        ]);
        #队列
        Redis::rpush('songshu:queue',json_encode([
            'work_type'=>4,
            'data'=>[
                'type'=>$post['status']==1?2:1,
                'id'=>$id,
            ]
        ]));
        #日志
        if($post['status']==1){
            DB::table('prohibit_log')->insert([
                    'uid'=>$id,
                    'status'=>$post['status'],
                    'add_time'=>time(),
                    'msg'=>'',
                ]);
        }
        return response()->json([
            'status'=>$bool?1:0,
            'info'=>$bool?'success':'fail',
        ]);
    }

    public function ajax_up_level($id){
        $post = request()->only(['level']);
        if($post['level']==1){
            $bool = DB::table('user_tree')->where('uid',$id)->update([
                'user_level'=>$post['level'],
                'up_vip_time'=>time(),
            ]);
            #入库消息 && 发送通知
            if($bool){
                $add_msg = DB::table('message')->insert([
                    'uid'=>$id,
                    'is_system'=>0,
                    'type'=>3,
                    'title'=>'恭喜您升级为超级会员',
                    'content'=>'恭喜您，在" . $day . "达到升级超级会员条件，我们现已将您的账户升级为超级会员！',
                    'add_time'=>time(),
                    'click_url'=>"songshu://://songshutoutiao.com/native?url=vip_center&need_login=1",
                    'button_name'=>'去查看',
                    'show_type'=>3,
                ]);
                if($add_msg){
                    $day = date('Y/m/d H:i');
                    $data = array(
                        'work_type' => "4",
                        'title' => "恭喜您升级为超级会员",
                        'text' => "恭喜您，在" . $day . "达到升级超级会员条件，我们现已将您的账户升级为超级会员！",
                        'reg_id' => $uid,
                        'list' => array(
                            'work_type'=>"4",
                            'type'=>"1",//1升级为超级会员  2升级为合伙人
                            'click_url'=>'songshu://://songshutoutiao.com/native?url=vip_center&need_login=1'
                       
                        )
                    );
                    $data = json_encode($data);
                    Redis::rpush('queue:jpush',$data);
                }
            }
        }elseif($post['level']==2){
            $bool = User::separate_tree($id);
        }
        

        return response()->json([
            'status'=>$bool?1:0,
            'info'=>$bool?'success':'fail',
        ]);
    }

    public function ajax_up_diversion($id){
        $post = request()->only(['diversion']);
        $bool = DB::table('user_tree')->where('id',$id)->update(['diversion'=>$post['diversion']]);
        return response()->json([
            'status'=>$bool?1:0,
            'info'=>$bool?'success':'fail',
        ]);
    }

    public function ajax_diversion($id){
        $status = request()->input('diversion');
        if(!in_array($status, [0,2])){
            return ['status'=>0,'info'=>'fail'];
        }
        DB::table('user_tree')->where('id',$id)->update(['diversion'=>$status]);
        return ['status'=>1,'info'=>'fail'];
    }

    /**
     * @name 合伙人收益
     */
    public function money($id){
        $list = DB::table('partner_daily_data')->where('uid',$id);
        $this->_search($list, $search);
        $list = $list->orderBy('id','desc')->paginate(20);
        $uids = get_array_keys($list->items(),'uid');
        $users = DB::table('user_tree')->whereIn('uid',$uids)->get()->toArray();
        $users = arrays_set_key($users,'uid');

        foreach($list->items() as &$item){
            $item->user = $users[$item->uid];
        }
        $group = DB::table('partner_daily_data')
        ->select(DB::raw("sum(coin_all) coin_all,sum(app_stage) app_stage,sum(app_tribute) app_tribute,sum(after_divide_into_coin) after_divide_into_coin,sum(subsidy_coin) subsidy_coin"))
        ->where('uid',$id)->first();

        #dump($group);
        $userdata = DB::table('userdata')->where('id',$id)->first(['nickname']);
        return view('Admin.User.money')->with([
            'list' => $list,
            '_search'=>$search,
            'nickname'=>urldecode($userdata->nickname),
            'group'=>$group,
        ]);
    }

    /**
     * @menu 汇率设置
     */
    public function set_rate(){
        if(request()->isMethod('post')){
            $param = request()->only(['app_proportion','partner_proportion']);
            DB::table('app_config')->where('id',1)->update($param);
            return redirect('/user/set_rate');
        }
        $data = DB::table('app_config')->where('id',1)->first();
        return view('Admin.User.set_rate')->with([
            'data'=>$data,
        ]);
    }
    /**
     * @menu 合伙人结算
     */
    public function checkout(){
        $list = DB::table('partner_monthly_data');
        $this->_search($list, $search);
        $list = $list->orderBy('id','desc')->paginate(20);

 
        $month = date('Ym',strtotime("-1 month"));
        
        return view('Admin.User.checkout')->with([
            'list'=>$list,
            '_search'=>$search,
            'month'=>$month,
        ]);
    }

    public function checkout_done(){
        $param = request()->only(['month']);
        #$param['month'] = 201811;
        $exists = DB::table('partner_monthly_data')->where('day',$param['month'])->exists();
        if($exists){
            #return redirect('user/checkout')->withErrors(['已经结算不能重复结算']);
            #dd("已经结算不能重复结算");
        }



        $y_time = strtotime($param['month']);
        $sday = date('Ymd',$y_time);
        $eday = date('Ymd',strtotime("+1 month",$y_time)-1);
        
        $group = DB::table('partner_daily_data')
        ->select(DB::raw("sum(coin_all) coin_all,sum(subsidy_coin) subsidy_coin,sum(divide_into_coin) divide_into_coin,sum(after_divide_into_coin) after_divide_into_coin, sum(subgrade_coin) subgrade_coin, sum(added_count) added_count,uid"))
        ->where('ym',$param['month'])->groupBy('uid')->get()->toArray();
        #月活跃总数
        $uids = DB::table('partner_daily_data')->distinct()->where('ym',$param['month'])->pluck('uid')->toArray();
        #付款信息
        $pays = DB::table('partner_checkout_log')->whereIn('uid',$uids)->get()->toArray();
        $pays = arrays_set_key($pays,'uid');


        /*
        $huoyue = DB::table('everyday_contribution')->select(DB::raw('count(id) as count,uid'))->where([
            ['frequency_all','>',2]
        ])->whereIn('uid',$uids)->whereBetween('day',[$sday,$eday])->groupBy('uid')->get()->toArray();
        $huoyue = arrays_set_key($huoyue,'uid');
        */

        $app_config = DB::table('app_config')->where('id',1)->first();

        $users = DB::table('user_tree')->whereIn('uid',$uids)->select('uid','left','right','tree_id','hight')->get()->toArray();
        $users = arrays_set_key($users,'uid');
       
        foreach($group as &$list){
            #$list->active_count = $huoyue[$list->uid]->count??0;
            $list->money_all = round($list->subsidy_coin/1000,2) + round($list->divide_into_coin * ($app_config->partner_proportion/1000),2);

            #$list->divide_into_coin = round($list->divide_into_coin * ($app_config->partner_proportion/1000),2);
            #$list->after_divide_into_coin = round($list->after_divide_into_coin * ($app_config->partner_proportion/1000),2);
            $list->pay_status = isset($pays[$list->uid])?1:0;

            #childuid
            $childuids = DB::table('user_tree')->where([
                ['tree_id','=',$users[$list->uid]->tree_id],
                ['left','>',$users[$list->uid]->left],
                ['right','<',$users[$list->uid]->right],
            ])->pluck('uid')->toArray();

            $list->active_count = DB::table('everyday_contribution')->where([
                ['frequency_all','>',2]
            ])->whereIn('uid',$childuids)->whereBetween('day',[$sday,$eday])->count();
        }


        return view('Admin.User.checkout_done')->with([
            'list'=>$group,
            'month'=>$param['month'],
            'partner_proportion'=>$app_config->partner_proportion,
        ]);
    }

    /**
     * @name 合伙人结算
     */
    public function done(){
        if( request()->isMethod('post') ){
            $param = request()->only(['month']);
            #$param['month'] = 201811;
            $exists = DB::table('partner_monthly_data')->where('day',$param['month'])->exists();
            if($exists){
                return redirect('user/checkout')->withErrors(['已经结算不能重复结算']);
            }
            if($param['month']>=date('Ym')){
                return redirect('user/checkout')->withErrors(['还没有到结算日期']);
            }

            $y_time = strtotime($param['month']);
            $sday = date('Ymd',$y_time);
            $eday = date('Ymd',strtotime("+1 month",$y_time)-1);
            
            $group = DB::table('partner_daily_data')
            ->select(DB::raw("sum(coin_all) coin_all,sum(subsidy_coin) subsidy_coin,sum(divide_into_coin) divide_into_coin,sum(after_divide_into_coin) after_divide_into_coin, sum(subgrade_coin) subgrade_coin, sum(added_count) added_count,uid"))
            ->where('ym',$param['month'])->groupBy('uid')->get()->toArray();
            #月活跃总数
            $uids = DB::table('partner_daily_data')->distinct()->where('ym',$param['month'])->pluck('uid')->toArray();
            $huoyue = DB::table('everyday_contribution')->select(DB::raw('count(id) as count,uid'))->where([
                ['frequency_all','>',2]
            ])->whereIn('uid',$uids)->whereBetween('day',[$sday,$eday])->groupBy('uid')->get()->toArray();
            $huoyue = arrays_set_key($huoyue,'uid');
            $app_config = DB::table('app_config')->where('id',1)->first();

            $users = DB::table('user_tree')->whereIn('uid',$uids)->select('uid','left','right','tree_id','hight')->get()->toArray();
            $users = arrays_set_key($users,'uid');
           
            $result = [];
            $datas = [];
            foreach($group as &$list){
                $list->active_count = $huoyue[$list->uid]->count??0;
                $list->money_all = round($list->subsidy_coin/1000,2) + round($list->divide_into_coin * ($app_config->partner_proportion/1000),2);
                $result[$list->uid] = $list->money_all;
                
                $datas[] = [
                    'uid'=>$list->uid,
                    'money_all'=>$list->money_all,
                    'subsidy_coin'=>$list->subsidy_coin,
                    'divide_into_coin'=>$list->divide_into_coin,
                    'proportions'=>$app_config->partner_proportion,
                    'after_divide_into_coin'=>$list->after_divide_into_coin,
                    'subgrade_coin'=>$list->subgrade_coin,
                    'active_count'=>$list->active_count,
                    'added_count'=>$list->added_count,
                    'day'=>$param['month'],
                ];
            }
            
            if(empty($datas)){
                return redirect('/User/checkout')->withErrors([$param['month'].'没有数据可结算']);
            }


            $all_bool = true;
            DB::beginTransaction();
            foreach($result as $uid=>$money){
                $info = DB::table('user_tree')->where('uid',$uid)->lockForUpdate()->first(['money']);
                $step1 = DB::table('partner_moneylog')->insert([
                    'uid'=>$uid,
                    'affect'=>$money,
                    'add_time'=>time(),
                    'current_money'=>$info->money+$money,
                ]);
                $step2 = DB::table('user_tree')->where('uid',$uid)->update([
                    'money'=>DB::raw("`money`+".$money),
                ]);
                if(!$info || !$step1 || !$step2){
                    DB::rollBack();
                    return redirect('/User/checkout')->withErrors(['事物失败']);
                }
            }
            if( DB::table('partner_monthly_data')->insert($datas) ){
                DB::commit();
                return redirect('/User/checkout')->with('success','结算成功');
           }else{
                DB::rollBack();
                return redirect('/User/checkout')->withErrors(['结算失败']);
           }
        }
    }


    public function onedone(){
        $param = request()->only(['uid','month']);
        if(!$param['uid'] || !$param['month']){
            dd('error');
        }
        $uid = $param['uid'];
        $app_config = DB::table('app_config')->where('id',1)->first();
        $y_time = strtotime($param['month']);
        $sday = date('Ymd',$y_time);
        $eday = date('Ymd',strtotime("+1 month",$y_time)-1);
        


        DB::beginTransaction();
        $has = DB::table('partner_checkout_log')->where('uid',$uid)->where('ym',$param['month'])->first();
        if($has){
            DB::rollBack();
            return redirect('/user/checkout')->withErrors(['不能重复结算']);
        }

        $group = DB::table('partner_daily_data')
        ->select(DB::raw("sum(coin_all) coin_all,sum(subsidy_coin) subsidy_coin,sum(divide_into_coin) divide_into_coin,sum(after_divide_into_coin) after_divide_into_coin, sum(subgrade_coin) subgrade_coin, sum(added_count) added_count"))
        ->where('uid',$uid)->where('ym',$param['month'])->first();

        $money=round($group->subsidy_coin/1000,2) + round($group->divide_into_coin * ($app_config->partner_proportion/1000),2);
        $info = DB::table('user_tree')->where('uid',$uid)->lockForUpdate()->first(['money']);
        $step1 = DB::table('partner_moneylog')->insert([
            'uid'=>$uid,
            'affect'=>$money,
            'add_time'=>time(),
            'type'=>3,
            'current_money'=>$info->money+$money,
            'desc'=>date('Y年m月',strtotime($param['month'])).'月收入结算',
        ]);
        $step2 = DB::table('user_tree')->where('uid',$uid)->update([
            'money'=>DB::raw("`money`+".$money),
            'total_money'=>DB::raw("`total_money`+".$money),
            ]);
        
        $step3 = DB::table('partner_monthly_data')->insert([
            'uid'=>$uid,
            'money_all'=>$money,
            'subsidy_coin'=>round($group->subsidy_coin/1000,2),
            'divide_into_coin'=>round($group->divide_into_coin * ($app_config->partner_proportion/1000),2),
            'proportions'=>$app_config->partner_proportion,
            'after_divide_into_coin'=>$group->after_divide_into_coin,
            'subgrade_coin'=>$group->subgrade_coin,
            'active_count'=>$huoyue,
            'added_count'=>$group->added_count,
            'day'=>$param['month'],
        ]);
        $step4 = DB::table('partner_checkout_log')->insert([
            'uid'=>$uid,
            'ym'=>$param['month'],
            'money'=>$money,
            'add_time'=>time(),
        ]);
        
        if( $step1!==false && $step2!==false && $step3!==false && $step4!==false){
            DB::commit();
            return redirect('user/checkout_done?month='.$param['month'])->withErrors(['结算成功']);
        }else{
            DB::rollBack();
        }
        return redirect('/user/checkout')->withErrors(['结算失败1']);
    }

    public function ajax_batch_done(){
        $param = request()->only(['ids']);
        $urls = explode(',', $param['ids']);

        $rs = [];
        foreach($urls as $line){
            $tmp = explode('.', $line);
            $rs [] = [
                'uid'=>$tmp[0],
                'month'=>$tmp[1],
            ];
        }

        foreach($rs as $row){
            $uid = $row['uid'];
            $param['month'] = $row['month'];
            $app_config = DB::table('app_config')->where('id',1)->first();
            $y_time = strtotime($param['month']);
            $sday = date('Ymd',$y_time);
            $eday = date('Ymd',strtotime("+1 month",$y_time)-1);
            


            DB::beginTransaction();
            $has = DB::table('partner_checkout_log')->where('uid',$uid)->where('ym',$param['month'])->first();
       
            if($has){
                DB::rollBack();
                return response()->json(['status'=>0, 'msg'=>'不能重复结算']);
            }

            $group = DB::table('partner_daily_data')
            ->select(DB::raw("sum(coin_all) coin_all,sum(subsidy_coin) subsidy_coin,sum(divide_into_coin) divide_into_coin,sum(after_divide_into_coin) after_divide_into_coin, sum(subgrade_coin) subgrade_coin, sum(added_count) added_count"))
            ->where('uid',$uid)->where('ym',$param['month'])->first();

            $money=round($group->subsidy_coin/1000,2) + round($group->divide_into_coin * ($app_config->partner_proportion/1000),2);
            $info = DB::table('user_tree')->where('uid',$uid)->lockForUpdate()->first(['money']);
            $step1 = DB::table('partner_moneylog')->insert([
                'uid'=>$uid,
                'affect'=>$money,
                'add_time'=>time(),
                'type'=>3,
                'current_money'=>$info->money+$money,
                'desc'=>date('Y年m月',strtotime($param['month'])).'月收入结算',
            ]);
            $step2 = DB::table('user_tree')->where('uid',$uid)->update([
                'money'=>DB::raw("`money`+".$money),
                'total_money'=>DB::raw("`total_money`+".$money),
                ]);
            
           
            $step3 = DB::table('partner_monthly_data')->insert([
                'uid'=>$uid,
                'money_all'=>$money,
                'subsidy_coin'=>round($group->subsidy_coin/1000,2),
                'divide_into_coin'=>round($group->divide_into_coin * ($app_config->partner_proportion/1000),2),
                'proportions'=>$app_config->partner_proportion,
                'after_divide_into_coin'=>$group->after_divide_into_coin,
                'subgrade_coin'=>$group->subgrade_coin,
                'active_count'=>$huoyue,
                'added_count'=>$group->added_count,
                'day'=>$param['month'],
            ]);
            $step4 = DB::table('partner_checkout_log')->insert([
                'uid'=>$uid,
                'ym'=>$param['month'],
                'money'=>$money,
                'add_time'=>time(),
            ]);
            
            if( $step1!==false && $step2!==false && $step3!==false && $step4!==false){
                DB::commit();
                return response()->json(['status'=>1, 'msg'=>'success']);
            }else{
                DB::rollBack();
            }
            
        }

       return response()->json(['status'=>1, 'msg'=>'success']);
    }

    /**
     * @name 合伙人详细
     */
    public function partner_info($uid){
        $today = date('Ymd');
        $day_info = DB::table('partner_daily_data')->where('uid',$uid)->where('day',$today)->first();
        if(!empty($day_info)){
            $day_info->divide_into_coin = number_format($day_info->divide_into_coin/1000,2);
            $day_info->subsidy_coin = number_format($day_info->subsidy_coin/1000,2);
        }
        $yestoday = DB::table('partner_daily_data')->where('uid',$uid)->where('day',date('Ymd',strtotime("-1 day")))->first();
        if(!empty($yestoday)){
            $yestoday->divide_into_coin = number_format($yestoday->divide_into_coin/1000,2);
            $yestoday->subsidy_coin = number_format($yestoday->subsidy_coin/1000,2);
        }

        $user = DB::table('user_tree')->where('uid',$uid)->first(['total_money']);

        //本月预估
        $this_month = User::nowmonth($user_tree);
        $data['this_month'] = $this_month;
        $time_m = date('Ym00');
        //上月预估
        $time_1m = date("Ym00", strtotime("-1 month"));
        $last_month = DB::table('partner_daily_data')->where('uid',$uid)->whereBetween('day',[$time_1m,$time_m])->sum('coin_all');
        if(empty($last_month)){
            $data['last_month'] = '￥0.00';
        }else{
            $data['last_month'] = "￥" . number_format((floor($last_month / 10) / 100),2,null,'');
        }
        #dump($data);
        return view('Admin.User.partner_info')->with([
            'day_info'=>$day_info,
            'user'=>$user,
            'data'=>$data,
            'yestoday'=>$yestoday,
        ]); 
    }

    /**
     * @name 今日新增
     */
    public function today_add($id){
        
    }

    /**
     * @name 封禁记录
     */
    public function prohibit($uid){
        $list = DB::table('prohibit_log')->where('uid',$uid);
        $list = $list->orderBy('id','desc')->paginate(20);
        return view('Admin.User.prohibit')->with([
            'list'=>$list,
            'status'=>Config::get_config_bykey('userdata_status'),
        ]); 
    }

    /**
     * @name 导流设置
     */
    public function ajax_invitation_code($uid){
        if( request()->isMethod('post') ){
            $param = request()->only(['invitation_code']);
            if(DB::table('userdata')->where('invitation_code',$param['invitation_code'])->exists() ){
                return \Redirect::back()->with('msg', '失败：邀请码已存在');
            }
            DB::beginTransaction();
            $step1 = DB::table('userdata')->where('id',$uid)->update(['invitation_code'=>$param['invitation_code']]);
            $step2 = DB::table('user_tree')->where('uid',$uid)->update(['invitation_code'=>$param['invitation_code']]);
            if($step1 && $step2){
                if(config('app')['env']=='production'){
                    $curl = curl_init();
                    $url = 'http://songshutoutiao.com/curl/qcode_image_save.php?uid='.$uid.'&invitation_code='.$param['invitation_code'];
                    curl_setopt($curl, CURLOPT_URL, $url);
                    curl_setopt($curl, CURLOPT_HEADER, 0);
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                    $data = curl_exec($curl);
                    curl_close($curl);
                }
                DB::commit();
            }else{
                DB::rollBack();
            }
            return \Redirect::back()->with('msg', '修改成功');
        }
        $data = DB::table('userdata')->where('id',$uid)->first(['id','invitation_code']);
        return view('Admin.User.ajax_invitation_code')->with([
            'data'=>$data,
        ]); 
    }

    public function ajax_jurisdiction($uid){
        $param = request()->only(['jurisdiction']);
        $bool = DB::table('user_tree')->where('uid',$uid)->update(['jurisdiction'=>$param['jurisdiction']]);
        if($bool!==false){
            return response()->json([
                'status'=>1,
                'jurisdiction'=>1,
                'data'=>$param['jurisdiction']?'有':'无',
                'uid'=>$uid
            ]);
        }else{
            return response()->json([
                'status'=>0,
                'jurisdiction'=>0,
                'data'=>$param['jurisdiction']?'有':'无',
                'uid'=>$uid
            ]);
        }
    }

    public function ajax_adv_switch($uid){
        $param = request()->only(['adv_switch']);
        $bool = DB::table('user_tree')->where('uid',$uid)->update(['adv_switch'=>$param['adv_switch']]);
        if($bool!==false){
            return response()->json([
                'status'=>1,
                'adv_switch'=>1,
                'data'=>$param['adv_switch']?'有':'无',
                'uid'=>$uid
            ]);
        }else{
            return response()->json([
                'status'=>0,
                'jurisdiction'=>0,
                'data'=>$param['adv_switch']?'有':'无',
                'uid'=>$uid
            ]);
        }
    }
}